package com.franklin.ideaplugin.easytesting.controllerclient.annotation;

import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.controllerclient.IMethodParameterProcessor;
import com.franklin.ideaplugin.easytesting.controllerclient.beans.MethodData;
import com.franklin.ideaplugin.easytesting.controllerclient.request.RequestPosition;
import org.springframework.web.bind.annotation.RequestHeader;

import java.lang.annotation.Annotation;
import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2023/6/28
 */
public class HeaderParameterProcessor implements IMethodParameterProcessor {

    private final static Class<RequestHeader> ANNOTATION = RequestHeader.class;

    @Override
    public Class<? extends Annotation> getAnnotationType() {
        return ANNOTATION;
    }

    @Override
    public boolean processParameter(MethodData methodData, Annotation annotation, Integer parameterIndex, Class<?> parameterType) {
        if (Objects.isNull(annotation) || !annotation.annotationType().isAssignableFrom(ANNOTATION)){
            return false;
        }
        RequestHeader requestHeader = ANNOTATION.cast(annotation);
        methodData.getParamPositions().put(parameterIndex, RequestPosition.HEADER);
        if (StrUtil.isNotBlank(requestHeader.value())){
            methodData.getParamKeys().put(parameterIndex, requestHeader.value());
        }else if (StrUtil.isNotBlank(requestHeader.name())){
            methodData.getParamKeys().put(parameterIndex, requestHeader.name());
        }else {
            methodData.getParamKeys().put(parameterIndex, parameterIndex.toString());
        }
        return true;
    }

}
